import simpleGit from 'simple-git'
import { writeFileSync } from 'fs'
import { join } from 'path'

// 配置
const config = {
  outputFile: [
    'CHANGELOG.md',
    'packages/code-blocks-editor/src/assets/markdown/CHANGELOG.md'
  ],
  repoPath: '.',
  maxCommits: 100, // 最多显示的提交数量
  commitTypeEmojis: {
    feat: '✨',
    fix: '🐛',
    docs: '📝',
    style: '💄',
    refactor: '♻️',
    perf: '⚡️',
    test: '✅',
    build: '🔧',
    ci: '👷',
    chore: '🔨',
    revert: '⏪'
  },
  defaultEmoji: '🔄',
  // 分支颜色
  branchColors: {
    master: '#007bff',
    main: '#007bff',
    develop: '#28a745',
    release: '#fd7e14',
    hotfix: '#dc3545'
  },
  defaultBranchColor: '#6c757d'
}

function parseCommitMessage(message) {
  const regex = /^(\w+)(?:\(([^)]+)\))?: (.+)/
  const match = message.match(regex)

  if (match) {
    return {
      type: match[1],
      scope: match[2] || '',
      subject: match[3]
    }
  }

  return {
    type: 'other',
    scope: '',
    subject: message
  }
}

// 获取当前分支
async function getCurrentBranch(git) {
  const branchSummary = await git.branch()
  return branchSummary.current
}

// 获取所有分支
async function getAllBranches(git) {
  const branchSummary = await git.branch()
  return Object.keys(branchSummary.branches)
}

// 生成Markdown时间线
async function generateTimeline() {
  const git = simpleGit(config.repoPath)

  // 获取当前分支
  const currentBranch = await getCurrentBranch(git)

  // 获取所有分支
  const allBranches = await getAllBranches(git)

  // 获取所有提交记录，包括所有分支
  const log = await git.log(['--all', '--date-order', `-n${config.maxCommits}`])

  // 获取分支信息
  const branchInfo = {}

  for (const branch of allBranches) {
    try {
      const branchCommit = await git.revparse([branch])
      branchInfo[branchCommit] = branch
    } catch (error) {
      console.error(`无法获取分支 ${branch} 的信息:`, error)
    }
  }

  // 按日期分组
  const commitsByDate = {}

  log.all.forEach((commit) => {
    const date = new Date(commit.date)
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`

    if (!commitsByDate[dateStr]) {
      commitsByDate[dateStr] = []
    }

    // 添加分支信息
    commit.branches = []
    for (const hash in branchInfo) {
      if (commit.hash.startsWith(hash) || hash.startsWith(commit.hash)) {
        commit.branches.push(branchInfo[hash])
      }
    }

    commitsByDate[dateStr].push(commit)
  })

  // 生成Markdown内容
  let markdown = '### 📖 项目提交历史\n\n'

  // 添加图例
  markdown += '#### 图例\n\n'
  markdown += '| 类型 | 描述 |\n'
  markdown += '| --- | --- |\n'

  for (const [type, emoji] of Object.entries(config.commitTypeEmojis)) {
    markdown += `| ${emoji} ${type} | ${getCommitTypeDescription(type)} |\n`
  }

  markdown += '\n'

  // 按日期倒序排列
  const sortedDates = Object.keys(commitsByDate).sort().reverse()

  sortedDates.forEach((date) => {
    markdown += `#### ${date}\n\n`

    commitsByDate[date].forEach((commit) => {
      const { type, scope, subject } = parseCommitMessage(commit.message)
      const emoji = config.commitTypeEmojis[type] || config.defaultEmoji
      const scopeText = scope ? `**${scope}**` : ''

      // 分支标签
      let branchTags = ''
      if (commit.branches && commit.branches.length > 0) {
        branchTags = commit.branches
          .map((branch) => {
            const color =
              config.branchColors[branch] || config.defaultBranchColor
            return `<span style="background-color: ${color}; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.8em;">${branch}</span>`
          })
          .join(' ')
        branchTags = ` ${branchTags}`
      }

      markdown += `- ${emoji} ${scopeText} ${subject}${branchTags}\n`

      // 提交详情
      const time = new Date(commit.date).toLocaleTimeString()
      markdown += `  <small><i>提交者: ${commit.author_name} &lt;${commit.author_email}&gt; | 时间: ${time} | 提交ID: [${commit.hash.substring(0, 7)}](https://gitee.com/wifi-skew-f/code-blocks/commit/${commit.hash})</i></small>\n\n`
    })
  })

  // 写入多个文件
  config.outputFile.forEach((outputFile) => {
    writeFileSync(join(config.repoPath, outputFile), markdown)
    console.log(`时间线已生成到 ${outputFile}`)
  })
}

// 获取提交类型的描述
function getCommitTypeDescription(type) {
  const descriptions = {
    feat: '新功能',
    fix: '修复Bug',
    docs: '文档更新',
    style: '代码格式修改',
    refactor: '代码重构',
    perf: '性能优化',
    test: '测试',
    build: '构建系统或外部依赖更改',
    ci: 'CI配置更改',
    chore: '其他更改',
    revert: '回退'
  }

  return descriptions[type] || '其他更改'
}

// 执行生成
generateTimeline().catch((err) => {
  console.error('生成时间线时出错:', err)
})
